package com.tc.biz.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.tc.activiti.util.user.UserUtil;
import com.tc.activiti.util.id.IdGenerator;
import com.tc.base.constants.StateEnum;
import com.tc.base.entity.APIResult;
import com.tc.biz.entity.BpmnApproval;
import com.tc.biz.entity.BpmnCopyProcess;
import com.tc.biz.entity.DrainagePipeMaintainence;
import com.tc.biz.entity.SysUser;
import com.tc.biz.service.BpmnApprovalService;
import com.tc.biz.service.BpmnCopyProcessService;
import com.tc.biz.service.IDrainagePipeMainService;
import com.tc.activiti.util.BeanUtils;
import com.tc.biz.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.javax.el.ExpressionFactory;
import org.activiti.engine.impl.javax.el.ValueExpression;
import org.activiti.engine.impl.juel.ExpressionFactoryImpl;
import org.activiti.engine.impl.juel.SimpleContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;

import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author zengqingfa
 * @date 2019/11/4 16:32
 * @description 管养控制器
 * @email zengqingfa_java@163.com
 */
@Api(tags = "管养控制器", value = "管养控制器")
@RestController
@RequestMapping("/bpmn/drainagePipe")
public class DrainagePipeMainController {

    protected static final Logger logger = LoggerFactory.getLogger(DrainagePipeMainController.class);

    @Autowired
    protected IDrainagePipeMainService drainagePipeMainService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    protected IdGenerator idGenerator;

    @Value("${is.skip.first.node}")
    protected Boolean isSkipFirstNode;

    @Autowired
    protected BpmnCopyProcessService processService;

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected IUserService userService;

    @Autowired
    protected BpmnApprovalService bpmnApprovalService;

    @Autowired
    protected BpmnCopyProcessService bpmnCopyProcessService;

    /**
     * 启动管养审批流程
     *
     * @param drainagePipeMaintainence
     * @param request
     * @return
     */
    @ApiOperation(value = "启动管养审批流程", notes = "启动管养审批流程")
    @RequestMapping(value = "/start/{processDefinitionId}", method = RequestMethod.POST)
    public APIResult startWorkflow(@RequestBody DrainagePipeMaintainence drainagePipeMaintainence,
                                   @PathVariable("processDefinitionId") String processDefinitionId, HttpServletRequest request, String userId) {
        APIResult result = new APIResult<>();
        ProcessInstance processInstance = null;
        logger.info("com.tc.biz.controller.DrainagePipeMainController.startWorkflow()--->processDefinitionId: {},userId:{} ", processDefinitionId, userId);
        try {
            //TODO 后续需要修改
            if (BeanUtils.isEmpty(userId)) {
                User user = UserUtil.getUserFromSession(request.getSession());
                // 用户未登录不能操作，实际应用使用权限框架实现，例如Spring Security、Shiro等
                if (user == null || StringUtils.isBlank(user.getId())) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            drainagePipeMaintainence.setCreateBy(userId);
            drainagePipeMaintainence.setCreateTime(new Date());
            drainagePipeMaintainence.setUpdateTime(new Date());
            drainagePipeMaintainence.setId(idGenerator.getId());
            Map<String, Object> variables = new HashMap<>();
            //启动流程实例，返回流程实例
            processInstance = drainagePipeMainService.start(drainagePipeMaintainence, variables, userId, processDefinitionId);
            //流程启动之后，设置各个节点的审批人信息
//            runtimeService.setVariables(processInstance.getId(),);
            //启动流程之后，新增一条记录到抄送人
            //获取抄送人集合
            List<SysUser> receiverList = drainagePipeMaintainence.getReceiverList();
            List<BpmnCopyProcess> list = new ArrayList<>();
            if (CollUtil.isNotEmpty(receiverList)) {
                for (SysUser sysUser : receiverList) {
                    BpmnCopyProcess rp = new BpmnCopyProcess();
                    rp.setId(idGenerator.getId());
                    rp.setCreateBy(userId);
                    rp.setCreateTime(new Date());
                    rp.setBussinessKey(drainagePipeMaintainence.getId());
                    rp.setProcessDefId(processDefinitionId);
                    rp.setProcessInstanceId(processInstance.getId());
                    //设置抄送人id
                    rp.setUserId(sysUser.getUserId().toString());
                    list.add(rp);
                }
            }
            if (BeanUtils.isNotEmpty(list)) {
                //批量新增抄送
                processService.batchInsert(list);
            }
            //判断是否跳过首节点
            if (isSkipFirstNode) {
                Task task = null;
                TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(userId).active();
                List<Task> todoList = query.list();//获取申请人的待办任务列表
                if (CollUtil.isNotEmpty(todoList)) {
                    for (Task tmp : todoList) {
                        if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                            task = tmp;//获取当前流程实例，当前申请人的待办任务
                            break;
                        }
                    }
                    if (BeanUtils.isNotEmpty(task.getId())) {
                        //保存一份数据到审批意见表中
                        BpmnApproval bpmnApproval = new BpmnApproval();
                        bpmnApproval.setAuditor(userId);
                        bpmnApproval.setTaskDefKey(task.getTaskDefinitionKey());
                        bpmnApproval.setOpinion(true);//设置审批意见
                        bpmnApproval.setCompleteTime(new Date());
                        bpmnApproval.setId(idGenerator.getId());
                        bpmnApproval.setProcDefId(task.getProcessDefinitionId());
                        bpmnApproval.setTaskId(task.getId());
                        bpmnApproval.setProcInstId(task.getProcessInstanceId());
                        bpmnApprovalService.insert(bpmnApproval);
                        taskService.complete(task.getId(), variables);
                    }
                }
            }
            result.setCause(processInstance.getId());
            result.setMessage("流程启动成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/drainagePipe/start/" + processDefinitionId, e);
        }
        return result;
    }


    /**
     * 通过任务id查询任务详情数据
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "通过任务id查询任务详情数据", notes = "通过任务id查询任务详情数据")
    @RequestMapping(value = "/processInstance/running/detail", method = RequestMethod.POST)
    public APIResult<DrainagePipeMaintainence> findRunningProcessInstanceDetail(@RequestBody HashMap<String, Object> map) {
        APIResult<DrainagePipeMaintainence> result = new APIResult<>();
        String taskId = (String) map.get("taskId");
        String status = (String) map.get("status");
        if (!status.equals("todo") && !status.equals("complete"))
            throw new RuntimeException("status is must todo or complete");
        if (BeanUtils.isEmpty(taskId)) throw new RuntimeException("taskId is should not null");
        String processInstanceId = null;
        DrainagePipeMaintainence drainagePipeMaintainence = new DrainagePipeMaintainence();
        try {
            if (status.equals("todo")) {//待办 todo
                TaskQuery taskQuery = taskService.createTaskQuery();
                Task task = taskQuery.taskId(taskId).singleResult();
                processInstanceId = task.getProcessInstanceId();
                drainagePipeMaintainence = drainagePipeMainService.findByProcessInstanceId(processInstanceId);
            }
            if (status.equals("complete")) {     //  ""已办 complete
                HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
                processInstanceId = historicTaskInstance.getProcessInstanceId();
                drainagePipeMaintainence = drainagePipeMainService.findByProcessInstanceId(processInstanceId);
                //已办需要回显意见
                BpmnApproval bpmnApproval = bpmnApprovalService.findByTaskId(taskId);
                if (BeanUtils.isNotEmpty(bpmnApproval)) {
                    drainagePipeMaintainence.setOpinion(bpmnApproval.getOpinion());//同意/拒绝
                    drainagePipeMaintainence.setComment(bpmnApproval.getComment()); //评论 原因
                }
            }
            if (BeanUtils.isNotEmpty(processInstanceId)) {
                String startedBy = drainagePipeMainService.getStartedBy(taskId);
                SysUser user = userService.selectByPrimaryKey(new Long(startedBy));
                //设置流程是由谁发起的
                drainagePipeMaintainence.setStartByUser(user);
                drainagePipeMaintainence.setTaskId(taskId);
                //设置抄送人
                List<String> receiverList = bpmnCopyProcessService.findReceiverByProceInstanceId(processInstanceId);
                List<SysUser> list = new ArrayList<>();
                if (BeanUtils.isNotEmpty(receiverList)) {
                    for (String s : receiverList) {
                        SysUser sysUser = userService.selectByPrimaryKey(new Long(s));
                        list.add(sysUser);
                    }
                }
                drainagePipeMaintainence.setReceiverList(list);
            }
            result.setData(drainagePipeMaintainence);
            result.setMessage("查询任务详情数据成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/drainagePipe/processInstance/running/detail", e);
        }
        return result;
    }


    /**
     * 通过流程实例id查询详情数据
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "通过流程实例id查询详情数据", notes = "通过流程实例id查询详情数据")
    @RequestMapping(value = "/processInstance/detail", method = RequestMethod.POST)
    public APIResult<DrainagePipeMaintainence> findDetailByProcessInstanceId(@RequestBody HashMap<String, Object> map) {
        APIResult<DrainagePipeMaintainence> result = new APIResult<>();
        String processInstanceId = (String) map.get("processInstanceId");
        try {
            DrainagePipeMaintainence drainagePipeMaintainence = drainagePipeMainService.findByProcessInstanceId(processInstanceId);
            result.setData(drainagePipeMaintainence);
            result.setMessage("查询任务详情数据成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/drainagePipe/processInstance/detail", e);
        }
        return result;
    }

    /**
     * 办理任务：
     *
     * @param map
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "通过任务id完成任务", notes = "通过任务id完成任务")
    @RequestMapping(value = "/complete", method = RequestMethod.POST)
    public APIResult complete(@RequestBody HashMap<String, Object> map, HttpServletRequest request) {
        APIResult result = new APIResult<>();
        String userId = (String) map.get("userId"); //  办理用户id
        String taskId = (String) map.get("taskId"); // 任务id
        Boolean opinion = (Boolean) map.get("opinion"); // 意见
        if (BeanUtils.isEmpty(opinion)) throw new RuntimeException("审批意见不能为空");
        if (BeanUtils.isEmpty(taskId)) throw new RuntimeException("taskId不能为空");
        String comment = (String) map.get("comment");
        try {
            //TODO 后续需要修改
            if (BeanUtils.isEmpty(userId)) {
                User user = UserUtil.getUserFromSession(request.getSession());
                // 用户未登录不能操作，实际应用使用权限框架实现，例如Spring Security、Shiro等
                if (user == null || StringUtils.isBlank(user.getId())) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            Task task = taskService.createTaskQuery().taskId(taskId).taskAssignee(userId).singleResult();
            if (task != null) {
                String taskDefKey = task.getTaskDefinitionKey();
                Map<String, Object> variables = new HashMap<>();
                if (taskDefKey.equals("adjust")) {//调整修改
                    variables.put("pipeDepartApproved", opinion);
                }
                if (taskDefKey.equals("confirm")) {//审批确认
                    variables.put("pipeDepartManagerApproved", opinion);
                }
                //增加批注信息
                // 由于流程用户上下文对象是线程独立的，所以要在需要的位置设置，要保证设置和获取操作在同一个线程中
                Authentication.setAuthenticatedUserId(userId);//批注人的名称  一定要写，不然查看的时候不知道人物信息
                //办理任务添加批注信息
                if (BeanUtils.isNotEmpty(comment)) {
                    taskService.addComment(taskId, task.getProcessInstanceId(), comment);
                }   //comment为批注内容：譬如如一些原因等等
                //保存一份数据到审批意见表中
                BpmnApproval bpmnApproval = new BpmnApproval();
                bpmnApproval.setCreateTime(new Date());
                bpmnApproval.setAuditor(userId);
                bpmnApproval.setAuditor(userId);
                bpmnApproval.setComment(comment);
                bpmnApproval.setTaskDefKey(task.getTaskDefinitionKey());
                bpmnApproval.setOpinion(opinion);//设置审批意见
                bpmnApproval.setCompleteTime(new Date());
                bpmnApproval.setId(idGenerator.getId());
                bpmnApproval.setProcDefId(task.getProcessDefinitionId());
                bpmnApproval.setTaskId(taskId);
                bpmnApproval.setProcInstId(task.getProcessInstanceId());
                bpmnApprovalService.insert(bpmnApproval);
                //说明assignee是该任务的办理人
                taskService.complete(taskId, variables);
                result.setMessage("任务办理成功");
                result.setState(200);
            } else {
                result.setMessage("任务办理失败，任务不存在");
                result.setState(404);
            }
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/drainagePipe/processInstance/running/detail", e);
        }
        return result;
    }


    /**
     * 获取下一个用户任务信息:可能会存在网关的情况，需要条件才能判断流程的走向，
     * 所以获取用户会有点问题。
     *
     * @param taskId 任务Id信息
     * @return 下一个用户任务用户组信息
     * @throws Exception
     */
    public TaskDefinition getNextTaskInfo(String taskId) throws Exception {
        ProcessDefinitionEntity processDefinitionEntity = null;
        String id = null;
        TaskDefinition task = null;
        //获取流程实例Id信息
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();
        //获取流程发布Id信息
        String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult().getProcessDefinitionId();
        processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(definitionId);
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //当前流程节点Id信息
        String activitiId = execution.getActivityId();
        //获取流程所有节点信息
        List<ActivityImpl> activitiList = processDefinitionEntity.getActivities();
        //遍历所有节点信息
        for (ActivityImpl activityImpl : activitiList) {
            id = activityImpl.getId();
            if (activitiId.equals(id)) {
                //获取下一个节点信息
                task = nextTaskDefinition(activityImpl, activityImpl.getId(), null, processInstanceId);
                break;
            }
        }
        return task;
    }


    /**
     * 下一个任务节点信息,
     * <p>
     * 如果下一个节点为用户任务则直接返回,
     * <p>
     * 如果下一个节点为排他网关, 获取排他网关Id信息, 根据排他网关Id信息和execution获取流程实例排他网关Id为key的变量值,
     * 根据变量值分别执行排他网关后线路中的el表达式, 并找到el表达式通过的线路后的用户任务
     *
     * @param activityImpl      流程节点信息
     * @param activityId        当前流程节点Id信息
     * @param elString          排他网关顺序流线段判断条件
     * @param processInstanceId 流程实例Id信息
     * @return
     */
    private TaskDefinition nextTaskDefinition(ActivityImpl activityImpl, String activityId, String elString, String processInstanceId) {
        PvmActivity ac = null;
        Object s = null;
        // 如果遍历节点为用户任务并且节点不是当前节点信息
        if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
            // 获取该节点下一个节点信息
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl.getActivityBehavior())
                    .getTaskDefinition();
            return taskDefinition;
        } else {
            // 获取节点所有流向线路信息
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
            List<PvmTransition> outTransitionsTemp = null;
            for (PvmTransition tr : outTransitions) {
                ac = tr.getDestination(); // 获取线路的终点节点
                // 如果流向线路为排他网关
                if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();
                    // 如果网关路线判断条件为空信息
                    if (StringUtils.isEmpty(elString)) {
                        // 获取流程启动时设置的网关判断条件信息
                        elString = getGatewayCondition(ac.getId(), processInstanceId);
                    }
                    // 如果排他网关只有一条线路信息
                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinition((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId,
                                elString, processInstanceId);
                    } else if (outTransitionsTemp.size() > 1) { // 如果排他网关有多条线路信息
                        for (PvmTransition tr1 : outTransitionsTemp) {
                            s = tr1.getProperty("conditionText"); // 获取排他网关线路判断条件信息
                            // 判断el表达式是否成立
                            if (isCondition(ac.getId(), StringUtils.trim(s.toString()), elString)) {
                                return nextTaskDefinition((ActivityImpl) tr1.getDestination(), activityId, elString,
                                        processInstanceId);
                            }
                        }
                    }
                } else if ("userTask".equals(ac.getProperty("type"))) {
                    return ((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior()).getTaskDefinition();
                } else {
                }
            }
            return null;
        }
    }

    /**
     * 查询流程启动时设置排他网关判断条件信息
     *
     * @param gatewayId         排他网关Id信息, 流程启动时设置网关路线判断条件key为网关Id信息
     * @param processInstanceId 流程实例Id信息
     * @return
     */
    public String getGatewayCondition(String gatewayId, String processInstanceId) {
        Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).singleResult();
        Object object = runtimeService.getVariable(execution.getId(), gatewayId);
        return object == null ? "" : object.toString();
    }

    /**
     * 根据key和value判断el表达式是否通过信息
     *
     * @param key   el表达式key信息
     * @param el    el表达式信息
     * @param value el表达式传入值信息
     * @return
     */
    public boolean isCondition(String key, String el, String value) {
        ExpressionFactory factory = new ExpressionFactoryImpl();
        SimpleContext context = new SimpleContext();
        context.setVariable(key, factory.createValueExpression(value, String.class));
        ValueExpression e = factory.createValueExpression(context, el, boolean.class);
        return (Boolean) e.getValue(context);
    }

    /**
     * 根据任务id返回流程实例对应所有的 批注信息
     *
     * @param taskId 任务信息
     * @return 批注信息
     */
    public List<Comment> getProcessComments(String taskId) {
        List<Comment> historyCommnets = new ArrayList<>();
        // 1) 获取流程实例的ID
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        //2）通过流程实例查询所有的(用户任务类型)历史活动
        List<HistoricActivityInstance> hais = historyService.createHistoricActivityInstanceQuery().processInstanceId(pi.getId()).activityType("userTask").list();
        //3）查询每个历史任务的批注
        for (HistoricActivityInstance hai : hais) {
            String historytaskId = hai.getTaskId();
            List<Comment> comments = taskService.getTaskComments(historytaskId);
            // 4）如果当前任务有批注信息，添加到集合中
            if (comments != null && comments.size() > 0) {
                historyCommnets.addAll(comments);
            }
        }
        //5）返回
        return historyCommnets;
    }

}


